﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CSC.FSVTracker.Domain.Abstract;
using CSC.FSVTracker.WebUI.Models;
using CSC.FSVTracker.WebUI.Helper;
using CSC.FSVTracker.Domain.Entities;

namespace CSC.FSVTracker.WebUI.Controllers
{
    public class AccountController : BaseController
    {
        
        /// <summary>
        /// User Repository.
        /// </summary>
        //private IUserRepository userRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="HomeController"/> class.
        /// </summary>
        /// <param name="repository">The repository.</param>
        public AccountController(IUserRepository repository) : base(repository){}

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// Logins the specified view model.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(LoginViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                User user = this.userRepository.Users.FirstOrDefault(u => u.LoginId == viewModel.LoginID);
                if (ViewModelHelper.AuthenticateUser(viewModel, user))
                {
                    Session["User"] = user;
                    return RedirectToAction("Index", "Home");
                }
                else 
                {
                    return View();
                }
            }
            else
            {
                return View();
            }
        }

        /// <summary>
        /// Called after the action method is invoked.
        /// </summary>
        /// <param name="filterContext">Information about the current request and action.</param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET"))
            {
                Session["User"] = null;
            }
            else
                if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "POST") && string.Equals(filterContext.ActionDescriptor.ActionName, "Login"))
            { 
                
            }
            base.OnActionExecuted(filterContext);
        }
    }
}
